﻿#include "qcarstatusform.h"
#include "ui_qcarstatusform.h"
#include<QMenu>
#include"qsimulation.h"
#include<qserialportinfo.h>
#include <QMessageBox>
#include <QTime>
QCarStatusForm::QCarStatusForm(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::QCarStatusForm)
{
    ui->setupUi(this);
    this->setCentralWidget(ui->tabWidget);

    m_nRecvNum = 0;
    m_nSendNum = 0;
    m_bOpen = false;

    ui->btn_open->setIcon(QIcon(":/images/images/OFF.png"));

    InitStatusBar();
    InitCommCmb();

    m_serial = new QSerialPort;

    connect( m_serial, SIGNAL(readyRead()), this, SLOT(slot_RecvPortData()));
    m_nReadBuffSize = 128 * 4;

    //网络部分初始化
    tcpClient = new QTcpSocket(this);   //实例化tcpClient
    tcpClient->abort();                 //取消原有连接

    connect(tcpClient, SIGNAL(readyRead()), this, SLOT(ReadData()));
    connect(tcpClient, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(ReadError(QAbstractSocket::SocketError)));

    connect(tcpClient,SIGNAL(connected()),this,SLOT(onConnected())); //连接上处理函数
    connect(tcpClient,SIGNAL(disconnected()),this,SLOT(onDisconnected())); //断开时的函数

    connect(&mTimer,SIGNAL(timeout()),this,SLOT(onTimeOut())); //连接

    curveGui = new QCurveGUI(this);


}

QCarStatusForm::~QCarStatusForm()
{
    delete ui;
}

void QCarStatusForm::controlCarMessage1(int model, int status, double speed, double angle)
{
    QString str=" ";
    if(model == 1)
    {
        str =tr( "原地模式");
    }
    else if(model == 2)
    {
        str = tr("平移模式");
    }
    else if(model == 3)
    {
        str = tr("车量模式");
    }
    else{
        str = "无效";
    }
    ui->line_pattern_2->setText(str);

    ui->line_status_2->setText(QString::number(status));

    ui->line_speed_2->setText(QString::number(speed));

    ui->line_angle_2->setText(QString::number(angle));

}

void QCarStatusForm::carStatus(bool light, bool standby1, bool standby2, bool right_enable,
                               bool left_enable, bool forword_enable, bool back_enable, bool stop_car)
{
    ui->line_light->setText(QString::asprintf("%s",light == 1?"开启":"关闭"));
    ui->line_func_1->setText(QString::asprintf("%s",standby1 == 1?"触发":"释放"));
    ui->line_func_2->setText(QString::asprintf("%s",standby2 == 1?"触发":"释放"));
    ui->line_right->setText(QString::asprintf("%s",right_enable == 1?"触发":"释放"));
    ui->line_left->setText(QString::asprintf("%s",left_enable == 1?"触发":"释放"));
    ui->line_head_enable->setText(QString::asprintf("%s",forword_enable == 1?"触发":"释放"));
    ui->line_back_enable->setText(QString::asprintf("%s",back_enable == 1?"触发":"释放"));
    ui->line_stop_car->setText(QString::asprintf("%s",stop_car == 1?"触发":"释放"));
}
//整车加载ui
void QCarStatusForm::AllCarStatus(int state, int mode, int control,
                                  int await, int error, double power)
{
    Q_UNUSED(power)
    ui->line_status->setText(QString::asprintf("%s",state == 0?"待机":"工作"));
    QString str=" ";
    if(mode == 1)
    {
        str =tr( "原地模式");
    }
    else if(mode == 2)
    {
        str = tr("平移模式");
    }
    else if(mode == 3)
    {
        str = tr("车量模式");
    }
    else{
        str = "异常模式";
    }
    ui->line_pattern->setText(str);
    if(control == 1)
    {
        str = tr("调试控制");
    }else if(control == 2)
    {
        str = tr("遥控控制");
    }
    else if(control == 3)
    {
        str = tr("调度控制");
    }
    else
    {
        str ="控制异常";
    }
    ui->line_func->setText(str);
     if(await == 0)
     {
         str = tr("立即进入");
     }
     else if(await == 2)
     {
         str = tr("不为0禁止待机");
     }
     else if(await == 3)
     {
         str = tr("禁止进入待机");
     }
     else
     {
         str = "无效";
     }
    ui->line_or_chose->setText(str);

    ui->line_fault_status->setText(QString::asprintf("%s",error == 1?"有故障":"无故障"));

}

void QCarStatusForm::AllCarStatus2(int error_level, int BMS_state, int high_volt,
                                   int charge_status, int tem_sys, double bat_v, double bat_i)
{
    QString str;
    if(error_level == 0){
        str = tr("正常");
    }else if(error_level == 1){
        str = tr("一级故障");
    } else if(error_level == 2)
    {
        str = tr("二级故障");
    }else
    {
        str = "三级故障";
    }
    ui->line_fault_grade->setText(str);
    if(BMS_state == 0){
        str = tr("自检");
    }else if(BMS_state == 1){
        str = tr("放电");
    } else if(BMS_state == 2)
    {
        str = tr("充电");
    }else
    {
        str = "保留";
    }
    ui->line_BMS->setText(str);

    ui->line_high_voltage->setText(QString::asprintf("%s",high_volt == 1?"高压闭合":"高压断开"));
    ui->line_relay->setText(QString::asprintf("%s",charge_status == 1?"预充完成":"正在预充"));
    if(tem_sys == 0){
        str = tr("未启动");
    }else if(error_level == 1){
        str = tr("冷却启动");
    } else if(error_level == 2)
    {
        str = tr("加热启动");
    }else
    {
        str = "故障";
    }
    ui->line_temp->setText(str);

    ui->line_voltage->setText(QString::number(bat_v));

    if(bat_i < 0.0001)
    {
        bat_i = 0;
    }

    ui->line_electricity->setText(QString::number(bat_i));
}

void QCarStatusForm::AllCarPart3(double turn_angle_1, double turn_angle_2,
                                 double turn_vel_1, double turn_vel_2)
{
    ui->line_one_wheel->setText(QString::number(turn_angle_1)); //角度
    ui->line_two_wheel->setText(QString::number(turn_angle_2)); //角度2
    ui->line_one_machine->setText(QString::number(turn_vel_1));
    ui->line_two_machine->setText(QString::number(turn_vel_2));
}

void QCarStatusForm::AllCarPart4(double speed, double angle)
{
    ui->line_speed->setText(QString::number(speed));
    ui->line_angle->setText(QString::number(angle));
}
/*************************************串口函数部分***********************************/
void QCarStatusForm::InitStatusBar()
{
    m_SerStateLbl = new QLabel();
    m_RecvNumLbl = new QLabel();
    m_SendNumLbl = new QLabel();
    m_ResetNumBtn = new QPushButton();

    connect(m_ResetNumBtn,SIGNAL(clicked()),this,SLOT(slot_ResetNumBtn_clicked()));

    m_SerStateLbl->setMinimumSize(180, 20);
    m_RecvNumLbl->setMinimumSize(180, 20); // 标签最小尺寸
    m_SendNumLbl->setMinimumSize(180, 20);

    ui->statusbar->addWidget(m_SerStateLbl);
    ui->statusbar->addWidget(m_RecvNumLbl);
    ui->statusbar->addWidget(m_SendNumLbl);
    ui->statusbar->addWidget(m_ResetNumBtn);


    SetSerState();
    SetRecvNum();
    SetSendNum();
    m_ResetNumBtn->setText(tr("复位计数"));


}

void QCarStatusForm::SetSerState()
{
    QString strState;
    if ( m_bOpen )
        strState = tr("打开");
    else
        strState = tr("关闭");

    m_SerStateLbl->setText(tr("串口状态：%1").arg(strState));
}

void QCarStatusForm::SetRecvNum()
{
    QString strRecvNum = QString::number(m_nRecvNum);
    m_RecvNumLbl->setText(tr("接收字节数：%1").arg(strRecvNum));
}

void QCarStatusForm::SetSendNum()
{
    QString strSendNum = QString::number(m_nSendNum);
    m_SendNumLbl->setText(tr("发送字节数：%1").arg(strSendNum));
}

bool QCarStatusForm::SetSerialPortParam(QSerialPort *serial)
{
    // 设置串口号
    QString strPortNum = ui->btn_serial_port->currentText();
    if (strPortNum == tr(""))
        return false;
    serial->setPortName(strPortNum);
    //设置波特率
    qint32 nBaudRate = ui->btn_band_rate->currentText().toInt();
    serial->setBaudRate(nBaudRate);

    //设置奇偶校验位
    int nParityType = ui->btn_check_bit->currentIndex();
    switch (nParityType) {
    case 0:
        serial->setParity(QSerialPort::NoParity);
        break;
    case 1:
        serial->setParity(QSerialPort::OddParity);
        break;
    case 2:
        serial->setParity(QSerialPort::EvenParity);
        break;
    case 3:
        serial->setParity(QSerialPort::MarkParity);
        break;
    case 4:
        serial->setParity(QSerialPort::SpaceParity);
        break;
    default:
        serial->setParity(QSerialPort::UnknownParity);
        break;
    }

    //设置数据位

    int nDataBits = ui->btn_data_bits->currentIndex();
    switch (nDataBits)
    {
    case 0:
        serial->setDataBits(QSerialPort::Data5);
        break;
    case 1:
        serial->setDataBits(QSerialPort::Data6);
        break;
    case 2:
        serial->setDataBits(QSerialPort::Data7);
        break;
    case 3:
        serial->setDataBits(QSerialPort::Data8);
        break;
    default:
        serial->setDataBits(QSerialPort::UnknownDataBits);
        break;
    }

    // 设置停止位
    int nStopBits = ui->btn_stop_bit->currentIndex();
    switch (nStopBits)
    {
    case 0:
        serial->setStopBits(QSerialPort::OneStop);
        break;
    case 1:
        serial->setStopBits(QSerialPort::OneAndHalfStop);
        break;
    case 2:
        serial->setStopBits(QSerialPort::TwoStop);
        break;
    default:
        serial->setStopBits(QSerialPort::UnknownStopBits);
        break;
    }

    return true;
}
/*************************************串口函数部分***********************************/
void QCarStatusForm::InitCommCmb()
{
    SetPortNumCmb();    // 串口号
    SetBaudCmb();       // 波特率
    SetDPaityCmb();     // 校验位
    SetDataBCmb();      // 数据位
    SetStopBCmb();      // 停止位
    SetStreamCmb();     // 流控制
}

void QCarStatusForm::SetPortNumCmb()
{
    QStringList commPortList = GetEnableCommPortQt();
    if(!commPortList.isEmpty())
        ui->btn_serial_port->addItems(commPortList);
}
//获取当前可用串口
QStringList QCarStatusForm::GetEnableCommPortQt()
{
    QStringList CommPortList;
    foreach(const QSerialPortInfo &info,QSerialPortInfo::availablePorts())
    {
       QSerialPort serial;
       serial.setPort(info);
       if(serial.open(QIODevice::ReadWrite))
       {
           CommPortList.append(serial.portName());
           serial.close();
       }
    }

    return CommPortList;
}
//以windows的方式获取串口
QStringList QCarStatusForm::GetEnableCommPortWin()
{
    QStringList CommPortList;

    QString strCommPath = tr("HKEY_LOCAL_MACHINE\\HARDWARE\\DEVICEMAP\\SERIALCOMM");
    QSettings *settings = new QSettings(strCommPath, QSettings::NativeFormat);
    QStringList keyList = settings->allKeys();

    if ( !keyList.isEmpty() )
    {
        for (int i = 0; i < keyList.count(); i++)
            CommPortList.append(GetComm(i));
    }

    return CommPortList;
}

QString QCarStatusForm::GetComm(int nIndex, bool bValue)
{
    QString strCommRet = tr("");
    HKEY hKey;

    // RegOpenKeyEx windowsApi 成功返回0 需要加<qt_windows.h>头文件
    if (::RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("HARDWARE\\DEVICEMAP\\SERIALCOMM"), 0, KEY_READ, &hKey) != 0)
    {
        QMessageBox::warning(this, tr("注册表"), tr("无法打开注册表！"), QMessageBox::Ok);
        return tr(""); // 无法打开注册表
    }

    QString strKeyMsg;      // 键名
    QString strValueMsg;    // 键值
    wchar_t keyName[256];   // 键名数组
    char keyValue[256];     // 键值数组

    ulong nKeySize = sizeof(keyName);
    ulong nValueSize = sizeof(keyValue);
    ulong nType;

    if (::RegEnumValue(hKey, nIndex, keyName, &nKeySize, nullptr, &nType, (BYTE*)keyValue, &nValueSize) == 0) // 列举键名
    {
        // 读取键名
        for (uint i = 0; i < nKeySize; i++)
        {
            if (keyName[i] != 0x00)
                strKeyMsg.append(keyName[i]);
        }

        // 读取键值
        for (uint j = 0; j < nValueSize; j++)
        {
            if (keyValue[j] != 0x00)
                strValueMsg.append(keyValue[j]);
        }

        if ( bValue )
            strCommRet = strValueMsg;
        else
            strCommRet = strKeyMsg;
    }//if
    else
    {
        ::RegCloseKey(hKey); // 关闭注册表
        return tr("");  // 无可用串口
    }

    return strCommRet;
}

void QCarStatusForm::SetBaudCmb()
{
    QStringList baudRList;
    baudRList.append(tr("110"));
    baudRList.append(tr("300"));
    baudRList.append(tr("600"));
    baudRList.append(tr("1200"));
    baudRList.append(tr("2400"));
    baudRList.append(tr("4800"));
    baudRList.append(tr("9600"));
    baudRList.append(tr("14400"));
    baudRList.append(tr("19200"));
    baudRList.append(tr("38400"));
    baudRList.append(tr("56000"));
    baudRList.append(tr("57600"));
    baudRList.append(tr("115200"));
    baudRList.append(tr("128000"));
    baudRList.append(tr("230400"));
    baudRList.append(tr("256000"));
    baudRList.append(tr("460800"));
    baudRList.append(tr("自定义"));

//    ui->btn_band_rate->clear(); //清除里面的数据
    ui->btn_band_rate->addItems(baudRList);
    ui->btn_band_rate->setCurrentIndex(0); //设置为230400

}

void QCarStatusForm::SetDPaityCmb()
{
  // 设置校验位
  QStringList  DPaityList;
  DPaityList.append(tr("NONE"));
  DPaityList.append(tr("ODD"));
  DPaityList.append(tr("EVEN"));
  DPaityList.append(tr("MARK"));
  DPaityList.append(tr("SPACE"));
  ui->btn_check_bit->clear();
  ui->btn_check_bit->addItems(DPaityList);
}

void QCarStatusForm::SetDataBCmb()
{
    //设置数据位
    ui->btn_data_bits->clear();
    for(int i = 5; i<=8; i++)
    {
        ui->btn_data_bits->addItem(QString::number(i));
    }
     ui->btn_data_bits->setCurrentIndex(3);
}

void QCarStatusForm::SetStopBCmb()
{
    ui->btn_stop_bit->clear();
    ui->btn_stop_bit->addItem(tr("None"));
    ui->btn_stop_bit->addItem(tr("one"));
    ui->btn_stop_bit->addItem(tr("two"));
    ui->btn_stop_bit->addItem(tr("onePointFit"));
    ui->btn_stop_bit->setCurrentIndex(1);
}

void QCarStatusForm::SetStreamCmb()
{

}

void QCarStatusForm::ReadData()
{
    QByteArray buffer = tcpClient->readAll();
    int  length =  buffer.count();
    if(!buffer.isEmpty())
    {
      for(int i = 0; i<length; i++)
      {
        ui->textEdit_2->append(QString::asprintf("%0.2X ",buffer.at(i)));
      }
//        ui->textEdit_2->append(buffer.toHex()); //16进制显示出来数据
    }
}

void QCarStatusForm::ReadError(QAbstractSocket::SocketError)
{
    tcpClient->disconnectFromHost();
    QMessageBox msgBox;
    msgBox.setText(tr("failed to connect server because %1").arg(tcpClient->errorString()));
    msgBox.exec();
    ui->btn_break->setEnabled(false);
    ui->btn_link->setEnabled(true);
    ui->btn_sendworks->setEnabled(false);
    ui->btn_charging->setEnabled(false);
}
//当连接上了
void QCarStatusForm::onConnected()
{
     mTimer.start(1000); //1秒钟发送一次
}

void QCarStatusForm::onDisconnected()
{
     mTimer.stop();
     makeSure = true;
}
//定时器发送


void QCarStatusForm::onTimeOut()
{

    if(makeSure)  // makeSure 为 true 时候, 表示为第一次发送报文确定
    {
        makeSure = false;
        //writeData[0] = 0x8e; //头
        confOnline.startFlag = 0x08e;
//        confOnline.head.TotalLength = 0x0000002d;

        memcpy(&confOnline.head.TotalLength,lengthOne,sizeof (lengthOne));  //真实数据不是45

//        qint64 adress = 0;
        memcpy(confOnline.head.SendAddress, sender1,sizeof(sender1));

        int port = 0;
        memcpy(&port, senderport,sizeof(senderport));
        confOnline.head.SendPort = port;

        memcpy(confOnline.head.ReceiveAddress, receive,sizeof(receive));


        memcpy(&port, receiveport,sizeof(receiveport));
        confOnline.head.ReceivePort = port;

        confOnline.head.Sn = 0x080;
        confOnline.head.Ac = 0x082;
        confOnline.head.AcSn = 0x081;
        confOnline.head.Num = 0x083;

        char msg[] = {0x02,0x01,0x00,0x00};
        memcpy(&confOnline.head.MsgFlag,msg,sizeof (msg));
//        confOnline.head.MsgFlag = 0x02010000;
//        QDataTime
        //时间
        QDateTime  curTimer = QDateTime::currentDateTime();
        QString  str = curTimer.toString("yyyy-MM-dd-hh-mm-ss-zzz0");
        bool ok;
        confOnline.head.time[0] =(uchar)str.mid(0,2).toUInt(&ok,16) & 0x0ff;
        confOnline.head.time[1] =(uchar)str.mid(2,2).toUInt(&ok,16) & 0x0ff;
        confOnline.head.time[2] =(uchar)str.mid(5,2).toUInt(&ok,16) & 0x0ff;
        confOnline.head.time[3] =(uchar)str.mid(8,2).toUInt(&ok,16) & 0x0ff;
        confOnline.head.time[4] =(uchar)str.mid(11,2).toUInt(&ok,16) & 0x0ff;
        confOnline.head.time[5] =(uchar)str.mid(14,2).toUInt(&ok,16) & 0x0ff;
        confOnline.head.time[6] =(uchar)str.mid(17,2).toUInt(&ok,16) & 0x0ff;
        confOnline.head.time[7] =(uchar)str.mid(19,2).toUInt(&ok,16) & 0x0ff;
        confOnline.head.time[8] =(uchar)str.mid(21,2).toUInt(&ok,16) & 0x0ff;

        char carflag[] = {0x72,0x03};
        memcpy(&confOnline.carFlag,carflag,sizeof (carflag));
 //       confOnline.carFlag = 0x7203;

        confOnline.endFlag = 0x08e;
        memset(writeData,0,sizeof (writeData));
        memcpy(writeData,&confOnline,sizeof(confOnline));

        tcpClient->write(writeData,45);
        QString  strW = "";
        strW.clear();
        for (int i = 0;i < 45;i++) {
            strW += QString::asprintf("%0.2X ",(uchar)writeData[i]);
        }
//        QByteArray bitarry;
//        bitarry = QByteArray(writeData);
//        QString strData = QString::asprintf("%s",writeData);
        ui->textEdit->clear();
        ui->textEdit->append(strW);//以16进制的数据写入
        sendDataNum++;
        sendDatabyte += 45;
        ui->line_send_frame->setText(QString::number(sendDataNum));
        ui->line_send_bit->setText(QString::number(sendDatabyte));
    }
    else {
        //发送状态报文数据
        platStatus.startFlag = 0x8e;

        platStatus.head.TotalLength = 0x69000000; //大端0x69

//        qint64 adress = 0;
        memcpy(platStatus.head.SendAddress, sender1,sizeof(sender1));
        int port = 0;
        memcpy(&port, senderport,sizeof(senderport));
        platStatus.head.SendPort = port;

        memcpy(platStatus.head.ReceiveAddress, receive,sizeof(receive));


        memcpy(&port, receiveport,sizeof(receiveport));
        platStatus.head.ReceivePort = port;

        platStatus.head.Sn = 0x0080;
        platStatus.head.Ac = 0x0082;
        platStatus.head.AcSn = 0x0081;
        platStatus.head.Num = 0x0083;

        platStatus.head.MsgFlag = 0x02000102; //0x020100002

        QDateTime  curTimer = QDateTime::currentDateTime();
        QString  str = curTimer.toString("yyyy-MM-dd-hh-mm-ss-zzz0");
        bool ok;
        platStatus.head.time[0] =(uchar)str.mid(0,2).toUInt(&ok,16);
        platStatus.head.time[1] =(uchar)str.mid(2,2).toUInt(&ok,16);
        platStatus.head.time[2] =(uchar)str.mid(5,2).toUInt(&ok,16);
        platStatus.head.time[3] =(uchar)str.mid(8,2).toUInt(&ok,16);
        platStatus.head.time[4] =(uchar)str.mid(11,2).toUInt(&ok,16);
        platStatus.head.time[5] =(uchar)str.mid(14,2).toUInt(&ok,16);
        platStatus.head.time[6] =(uchar)str.mid(17,2).toUInt(&ok,16);
        platStatus.head.time[7] =(uchar)str.mid(19,2).toUInt(&ok,16);
        platStatus.head.time[8] =(uchar)str.mid(21,2).toUInt(&ok,16);

        platStatus.carFlag = 0x0372; //大端7203

        memcpy(platStatus.workNum,workPass,sizeof (workPass)); //作业编号

        platStatus.InsLon = XB.InsLon /1e7; //获取经度
        platStatus.InsLat = XB.InsLat /1e7;
        platStatus.InsYaw = (double)XB.InsYaw;

        platStatus.battery =  (ushort)part2.power; //电量

        platStatus.speed = (ushort)part4.speed;
        platStatus.endFlag = 0x8e;

        memset(writeData,0,sizeof (writeData));
        memcpy(writeData,&platStatus,sizeof (platStatus));

        tcpClient->write(writeData,0x069);
        QString  strW = "";
        strW.clear();
        for (int i = 0;i < 0x069;i++) {
            strW += QString::asprintf("%0.2X ",(uchar)writeData[i]); //以两位16数据
        }
//        QByteArray bitarry;
//        bitarry = QByteArray(writeData);
        ui->textEdit->clear();
        ui->textEdit->append(strW);//以16进制的数据写入
        sendDataNum++;
        sendDatabyte += 0x069;
        ui->line_send_frame->setText(QString::number(sendDataNum));
        ui->line_send_bit->setText(QString::number(sendDatabyte));
    }

}

void QCarStatusForm::on_btn_keep_clicked()
{


}

void QCarStatusForm::on_btn_load_clicked()
{

}

void QCarStatusForm::on_btn_stop_clicked()
{

}

void QCarStatusForm::on_btn_start_clicked()
{

}
/***************************************************************************/
/*                             串口通信                                     */
/***************************************************************************/
// 打开/关闭串口
void QCarStatusForm::on_btn_open_clicked()
{
    if(m_serial->isOpen())
    {
       m_serial->close(); //关闭串口
       ui->btn_open->setText(tr("打开"));
       ui->btn_open->setIcon(QIcon(":/images/images/OFF.png"));
       m_bOpen = false;
       receiveOpen = false;
       SetSerState();
    }
    else  // 串口处于关闭状态，打开串口
    {
       if(!SetSerialPortParam(m_serial))
       {
           QMessageBox::critical(this,tr("Error"),tr("串口错误！"),QMessageBox::Ok);
           return;
       }
       // 打开串口

       if(!m_serial->open(QIODevice::ReadWrite))
       {
           QMessageBox::critical(this, tr("Error"), tr("串口不存在或者被其它程序占用！"), QMessageBox::Ok);
           return;
       }

       // 设置串口缓冲区大小
       m_serial->setReadBufferSize(m_nReadBuffSize);

       ui->btn_open->setText(tr("断开"));
       ui->btn_open->setIcon(QIcon(":/images/images/ON.png"));
       m_bOpen = true;
       receiveOpen = true;
       SetSerState();
       m_serial->setDataTerminalReady(true);
    }
}
/***************网络连接**********************/
void QCarStatusForm::on_btn_link_clicked()
{
    //链接
    QString addr = ui->comboBox->currentText();
    quint32 port = ui->comboBox_2->currentText().toUInt();
    tcpClient->connectToHost(addr,(quint16)port); //连接

    ui->btn_break->setEnabled(true);
    ui->btn_link->setEnabled(false);
    ui->btn_sendworks->setEnabled(true);
    ui->btn_charging->setEnabled(true);
}

void QCarStatusForm::on_btn_break_clicked()
{
    if(tcpClient->state() == QAbstractSocket::ConnectedState)
    {
        mTimer.stop();
        tcpClient->disconnectFromHost();
        ui->btn_break->setEnabled(false);
        ui->btn_link->setEnabled(true);
        ui->btn_sendworks->setEnabled(false);
        ui->btn_charging->setEnabled(false);
    }
}

void QCarStatusForm::on_btn_sendworks_clicked()
{
   //发送数据  作业完成报文
//    QByteArray stra;
//    QString msg = ui->textEdit->toPlainText(); //获取数据
//    ui->textEdit->clear(); //清空
//    QByteArray str = msg.toLocal8Bit();
//    if(!str.isEmpty())
//    {
//        tcpClient->write(str);
//    }
    finishWork.startFlag = 0x8e;
    finishWork.head.TotalLength = 0x4d000000; //77字节 大端模式 真的数据为0x0000004d
//    qint64 adress = 0;
    memcpy(finishWork.head.SendAddress, sender1,sizeof(sender1));
    int port = 0;
    memcpy(&port, senderport,sizeof(senderport));
    finishWork.head.SendPort = port;

    memcpy(finishWork.head.ReceiveAddress, receive,sizeof(receive));

    memcpy(&port, receiveport,sizeof(receiveport));
    finishWork.head.ReceivePort = port;

    finishWork.head.Sn = 0x80;
    finishWork.head.Ac = 0x82;
    finishWork.head.AcSn = 0x81;
    finishWork.head.Num = 0x83;

    finishWork.head.MsgFlag = 0x01000102;

    QDateTime  curTimer = QDateTime::currentDateTime();
    QString  str = curTimer.toString("yyyy-MM-dd-hh-mm-ss-zzz0");
    bool ok;
    finishWork.head.time[0] =(uchar)str.mid(0,2).toUInt(&ok,16);
    finishWork.head.time[1] =(uchar)str.mid(2,2).toUInt(&ok,16);
    finishWork.head.time[2] =(uchar)str.mid(5,2).toUInt(&ok,16);
    finishWork.head.time[3] =(uchar)str.mid(8,2).toUInt(&ok,16);
    finishWork.head.time[4] =(uchar)str.mid(11,2).toUInt(&ok,16);
    finishWork.head.time[5] =(uchar)str.mid(14,2).toUInt(&ok,16);
    finishWork.head.time[6] =(uchar)str.mid(17,2).toUInt(&ok,16);
    finishWork.head.time[7] =(uchar)str.mid(19,2).toUInt(&ok,16);
    finishWork.head.time[8] =(uchar)str.mid(21,2).toUInt(&ok,16);

    finishWork.carFlag = 0x0372;  //协议是7203,因为大小端问题

    memcpy(finishWork.workNum,workPass,sizeof (workPass)); //作业编号

    finishWork.endFlag = 0x8e;
    sendDataNum++;
    sendDatabyte += 77;
    ui->line_send_frame->setText(QString::number(sendDataNum));
    ui->line_send_bit->setText(QString::number(sendDatabyte));
   qint64 status = tcpClient->write(writeData,77);
   if(status > 0)
   {
       QMessageBox::information(this," ","数据发送成功");
   }

}

void QCarStatusForm::on_btn_charging_clicked()
{

    //发送数据
     QString msg = ui->textEdit->toPlainText(); //获取数据
     ui->textEdit->clear(); //清空
     QByteArray str = msg.toLocal8Bit();
     if(!str.isEmpty())
     {
         tcpClient->write(str);
     }
}

void QCarStatusForm::on_btn_clear_receive_clicked()
{
    //清空数据

     sendDataNum = 0;
     sendDatabyte = 0;
     receiveData = 0;
     receivebyte = 0;
     ui->textEdit_2->clear();
     ui->line_send_frame->setText("");
     ui->line_send_bit->setText("");
     ui->line_accept_frame->setText("");
     ui->line_accept_bit->setText("");

}

void QCarStatusForm::on_pushButton_clicked()
{

}

void QCarStatusForm::on_pushButton_2_clicked()
{

}

void QCarStatusForm::on_chose_file_clicked()
{

}

void QCarStatusForm::on_star_car_clicked()
{

}

void QCarStatusForm::on_textEdit_2_customContextMenuRequested(const QPoint &pos)
{
    Q_UNUSED(pos)
    QMenu *menuList = new QMenu(this);

    menuList->addAction(ui->act_socket);
    menuList->exec(QCursor::pos());
    delete menuList;
}

void QCarStatusForm::on_act_socket_triggered()
{

    QSimulation * simulate = new QSimulation();
    simulate->setWindowFlag(Qt::Window,true);
    simulate->setAttribute(Qt::WA_DeleteOnClose);
    QString str = windowTitle();
    simulate->setWindowTitle(str);
    simulate->show();
}
//当选择为最后一个，为自定义的时候
void QCarStatusForm::on_btn_band_rate_currentIndexChanged(int index)
{
    uint nCount = ui->btn_band_rate->count();
    if((unsigned)index == nCount-1) //当为最后的时候
    {
         ui->btn_band_rate->setEditable(true);
         ui->btn_band_rate->setItemText(index,tr(""));
    }
    else
    {
        ui->btn_band_rate->setEditable(false);
        ui->btn_band_rate->setItemText( nCount-1,tr("自定义"));
    }
}
// 复位计数
void QCarStatusForm::slot_ResetNumBtn_clicked()
{
    m_nSendNum = 0;
    m_nRecvNum = 0;
    SetSendNum();
    SetRecvNum();
}
//接收数据，并且解决对应数据解析。
void QCarStatusForm::slot_RecvPortData()
{
  // 槽函数，接收串口数据
    if(receiveOpen)
    {
        receiveOpen = false;
        char data[1024] = {"\n"};
        BYTE head[2] ={"\n"};
        int n = 0;
        BYTE checksum = 0; //校验和
        while (true) {
            m_serial->read(data,1);
            head[1] = head[0];
            head[0] = (BYTE)data[0];
            n++;
            if(n >50000)
            {
//               QMessageBox::critical(this,tr("Error"),tr("没有接收到数据或接收到的数据不正确！"),QMessageBox::Ok);
                receiveOpen = true;
                return;
            }

            if(head[0] == 0xaa && head[1] == 0x55)
            {
                m_serial->read(data,106);
                checksum = 0;
                break;
            }

        }
        //开始校验和
        for(int i = 0; i<105;i++)
        {
            checksum += (BYTE)data[i];
        }

        if(checksum == data[105])
        {
            memcpy(&XB,data,106); //复制到结构体中

            double InsLon = XB.InsLon / 1e7;  //经度
            double InsLat = XB.InsLat / 1e7;  //纬度
            float InsYaw = XB.InsYaw;         //朝向角

            ui->line_longitude->setText(QString::number(InsLon,'f',11));
            ui->line_latitude->setText(QString::number(InsLat,'f',11));
            ui->line_angle_3->setText(QString::number((double)InsYaw));
        }


        receiveOpen = true;
    }


}

void QCarStatusForm::on_act_curve_triggered()
{
    curveGui->setWindowTitle("曲线导航界面");
    curveGui->setWindowFlag(Qt::Window,true);
    curveGui->setWindowOpacity(1.2);
    curveGui->show();
}
